package com.flute.framework.monitor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.flute.tools.data.DataRecord;

public class DataRecordParser {

	public static boolean hasRecord(String path, long eventId) {
		if (!path.endsWith("/")) {
			path = path + "/";
		}
		path = FileHierarchy.getMachineRecordsFolder(path);

		File file = new File(path);
		File[] files = file.listFiles();
		if (files != null) {
			HashSet<String> logs = new HashSet<String>();
			for (File f : files) {
				logs.add(f.getName());
			}

			return logs.contains(eventId + ".log");
		}

		return false;
	}

	public static List<DataRecord> parseRecord(String path, long eventId,
			int page, int countPerPage) {
		if (!path.endsWith("/")) {
			path = path + "/";
		}
		path = FileHierarchy.getMachineRecordsFolder(path);

		File file = new File(path);
		File[] files = file.listFiles();
		Arrays.sort(files, new FileComparator());

		File[] neededFiles = new File[1];
		for (File f : files) {
			if (f.getName().contains(String.valueOf(eventId)) && f.isFile()
					&& f.getName().endsWith(".log")) {
				neededFiles[0] = f;
				break;
			}
		}

		List<MonitedValue> result = getValueList(neededFiles, page,
				countPerPage);

		List<DataRecord> datas = new ArrayList<DataRecord>();
		for (MonitedValue mv : result) {
			DataRecord dr = new DataRecord();
			for (String field : mv.getFields()) {
				dr.AddField(field, mv.getFieldValue(field));
			}
			datas.add(dr);
		}

		return datas;
	}

	private static List<MonitedValue> getValueList(File[] files, int page,
			int countPerPage) {
		List<MonitedValue> values = new ArrayList<MonitedValue>();
		if (files != null) {
			for (File f : files) {
				InputStream inputStream = null;
				LineNumberReader bfReader = null;
				InputStreamReader inReader = null;
				try {
					inputStream = new FileInputStream(f);
					inReader = new InputStreamReader(inputStream, "UTF8");
					bfReader = new LineNumberReader(inReader);

					int start = (page - 1) * countPerPage;
					bfReader.setLineNumber(start);
					while (bfReader.ready()) {
						String line = bfReader.readLine().trim();
						MonitedValue mv = MonitedValue.fromLogString(line);
						if (mv != null) {
							values.add(mv);
						}
						if (values.size() == countPerPage) {
							break;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					IOUtils.closeQuietly(bfReader);
					IOUtils.closeQuietly(inReader);
					IOUtils.closeQuietly(inputStream);
				}
			}
		}

		return values;
	}
}
